<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Validator;
use Illuminate\Validation\Rule;
use App\Model\Common\Slider;
use App\Model\Common\AdminLog;

class SliderController extends CommonController
{
    protected $defaultSort = 'rank';
    protected $defaultOrder = 'desc';

    public function add(Request $request)
    {
        if ('GET' == $request->method()) {
            return $this->fetch();
        } else {
            $types = ['home', 'login', 'register'];
            $data = $request->all();
            $validator = Validator::make($data, [
                'title' => 'required|min:1|max:24',
                'intro' => 'required|min:1|max:60',
                'type' => ['required', Rule::in($types)],
                'status' => ['required', Rule::in([0, 1])],
            ]);
            if ($validator->fails()) {
                return $this->output(10005, $validator->errors());
            }

            $path = $this->upload('slider_img');

            if (false === $path) {
                return $this->output(10005, $this->getUploadError());
            }

            $dataArray = [];
            $dataArray['title'] = $data['title'];
            $dataArray['intro'] = $data['intro'];
            $dataArray['img'] = $path;
            $dataArray['type'] = $data['type'];
            $dataArray['status'] = $data['status'];
            $m = new Slider();

            $re = $m->fillData($dataArray)->save();

            if ($re) {
                if (method_exists($m, 'refreshCache')) {
                    $m->refreshCache($m, 'insert');
                }
                AdminLog::log($request, $m);
                return $this->output(0, '新增成功', $re);
            } else {
                return $this->output(10001, '新增失败'.$m->getError(), null);
            }
        }
    }
}
